package cn.edu.nju.software.paymentSystem;

import java.sql.SQLException;

import cn.edu.nju.software.buyer.SystemA;
import cn.edu.nju.software.sellerSystem.SystemB;

public class SystemCPOAImp extends SystemCPOA {

	DBAccessor dba = new DBAccessor();

	@Override
	public int balance(String user, String password) {
		try {
			int res = dba.getBalance(user, password);
			if (res == -1) {
				System.out.println("Someone checked \"" + user
						+ "\"\'s balance. But there is no such record.");
			} else {
				System.out.println("\"" + user + "\"checked his balance. It's "
						+ res + " cents.");
			}
			return res;
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public boolean deal(String userA, String password, String userB,
			String purchaseNo, int amount) {
		try {
			System.out.println(userA + " want to order $" + amount / 100 + "."
					+ amount % 100 + " products from " + userB);
			boolean res = dba.paymentFrom(userA, password, amount, purchaseNo,
					userB);
			if (!res) {
				System.out.println("Order failed!");
				return res;
			}
			SellerClient sc = new SellerClient();
			SystemB b = sc.init(PaymentOptions.SELLER_NAME);
			if (b != null) {
				b.askToDeliver(purchaseNo);
			}
			System.out.println("Order success!");
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Order failed!");
			return false;
		}
	}

	@Override
	public void fail(String purchaseNo) {
		dealDone(purchaseNo, false);
		System.out.println("Purchase " + purchaseNo + " canceled!");
	}

	@Override
	public void success(String purchaseNo) {
		dealDone(purchaseNo, true);
		System.out.println("Purchase " + purchaseNo + " succeed!");
	}

	private void dealDone(String purchaseNo, boolean succeed) {
		try {
			dba.paymentTo(purchaseNo, succeed);
			SellerClient sc = new SellerClient();
			SystemB b = sc.init(PaymentOptions.SELLER_NAME);
			if (b != null) {
				if (succeed) {
					b.notifyDealDone(purchaseNo);
				} else {
					b.affirm(purchaseNo);
				}
			}
			BuyerClient bc = new BuyerClient();
			SystemA a = bc.init(PaymentOptions.BUYER_NAME);
			if (a != null && succeed) {
				a.dealSuccess(purchaseNo);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
